import 'dart:math';

import 'package:flutter_kit_dsp/flutter_kit_dsp.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../../tool/assets.dart';

class PassItem extends StatefulWidget {
  Passmodel pass;
  PassItem({super.key, required this.pass});

  @override
  State<PassItem> createState() => _PassItemState();
}

class _PassItemState extends State<PassItem> with WidgetsBindingObserver {
  final textControler = TextEditingController();
  double _keyboardHeight = 0.0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    textControler.text = '${widget.pass.freq}';
    textControler.addListener(() {
      String text = textControler.text;
      // 自动添加前导0
      if (text.isNotEmpty && text[0] == '0') {
        textControler.text = text;
        return;
      } else if (text.length > 1 && text[0] == '0' && text[1] != '.') {
        textControler.text = text.substring(1, text.length);
        return;
      }
    });
  }

  @override
  void dispose() {
    textControler.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    final bottomInset = WidgetsBinding.instance.window.viewInsets.bottom;
// 说明键盘从弹出 -> 收起
    if (_keyboardHeight > 0 && bottomInset == 0) {
      int freq = textControler.text.intValue;

      ///这里加个判断，只在值范围不正常的时候，在键盘隐藏时发送默认值。正常范围，在输入的时候已经发送了一遍，这里避免重复发送
      if (freq < 20 || freq > 20000) {
        freq = min(20000, max(20, freq));
        globalController.updatePassFreq(widget.pass, freq, isSend: true);
      }
    }
    // 说明键盘从收起 -> 弹出
    else if (_keyboardHeight == 0 && bottomInset > 0) {}
    // 更新当前记录
    _keyboardHeight = bottomInset;
  }

  Widget buildArrowBtn(bool isLeft) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      return myIconButton(
          enable: widget.pass.select,
          width: constraints.maxHeight * 0.825,
          height: constraints.maxHeight,
          iconName: isLeft ? assets.arrow_left : assets.arrow_right,
          onTap: () => globalController.changeFilterType(widget.pass, isLeft));
    });
  }

  @override
  Widget build(BuildContext context) {
    textControler.text = '${widget.pass.freq}';

    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      return Container(
        width: constraints.maxWidth,
        height: constraints.maxHeight,
        padding: const EdgeInsets.only(right: 5),
        decoration: boxDecorationWithColor(5, widget.pass.ishigh ? const Color(0xFFD67B9F) : const Color(0xFF9FCFE5)),
        child: Stack(
          children: [
            ///pass
            Positioned(
              left: -1,
              top: -1,
              bottom: -1,
              width: 20,
              child: Container(
                decoration: boxDecoration(5),
                child: RotatedBox(
                  quarterTurns: 3, // 旋转 90°（逆时针）
                  child: Center(child: Text(widget.pass.ishigh ? 'HIGH PASS' : 'LOW PASS', style: fontNormal)),
                ),
              ),
            ),

            ///右边
            Positioned(
                top: 0,
                bottom: 0,
                right: 0,
                left: 20,
                child: Column(
                  children: [
                    Container(height: 5),
                    Flexible(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      spacing: 10,
                      children: [
                        SizedBox(
                          width: 30,
                          child: InkWell(
                            child: Image.asset(assets.sub, width: 20, height: 20),
                            onTap: () => globalController.updatePassFreqWithAddOrSub(widget.pass, isAdd: false),
                          ),
                        ),
                        Container(
                          width: 100,
                          height: 30,
                          decoration: boxDecoration(5),
                          child: Center(
                            // child: Text('${widget.pass.freq}', style: fontNormal),
                            child: TextField(
                              cursorHeight: 14,
                              controller: textControler,
                              readOnly: !widget.pass.select,
                              enabled: widget.pass.select,
                              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black),
                              textAlign: TextAlign.center,
                              keyboardType: const TextInputType.numberWithOptions(decimal: false), // 数字键盘（不带小数点）
                              ///边框
                              decoration: const InputDecoration(
                                contentPadding: EdgeInsets.symmetric(vertical: 0), // 调整上下内边距
                                enabledBorder: OutlineInputBorder(
                                  // 默认边框
                                  borderSide: BorderSide(color: Colors.black, width: 0.2),
                                ),
                                focusedBorder: OutlineInputBorder(
                                    // 聚焦时边框
                                    // borderSide: BorderSide(color: Colors.red, width: 3),
                                    ),
                                border: OutlineInputBorder(), // 让边框生效
                              ),

                              ///输入规则限制
                              inputFormatters: [
                                LengthLimitingTextInputFormatter(5), // 限制输入最大长度为3
                                FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                                FilteringTextInputFormatter(
                                  RegExp(r'^\d*$'), // 允许数字
                                  allow: true,
                                ),
                              ],

                              ///响应方法
                              onTap: () {},
                              onChanged: (value) =>
                                  globalController.updatePassFreq(widget.pass, value.intValue, isSend: true),
                              onSubmitted: (value) {
                                FocusScope.of(context).unfocus();
                              },
                              onEditingComplete: () {
                                print('object======================>');
                              },
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 30,
                          child: InkWell(
                            child: Image.asset(assets.add, width: 20, height: 20),
                            onTap: () => globalController.updatePassFreqWithAddOrSub(widget.pass),
                          ),
                        )
                      ],
                    )),
                    Flexible(
                        child: Row(
                      children: [
                        Flexible(
                            child: Align(alignment: Alignment.centerRight, child: Text('FREQ', style: fontNormal))),
                        const SizedBox(width: 10),
                        Flexible(
                            flex: 4,
                            child: kSlider(
                                enable: widget.pass.select,
                                value: widget.pass.freq.toDouble(),
                                min: widget.pass.min_freq.toDouble(),
                                max: widget.pass.max_freq.toDouble(),
                                onChanged: (currentValue) {
                                  globalController.updatePassFreq(widget.pass, currentValue.toInt());
                                },
                                onChangedForSend: (currentValue) {
                                  globalController.updatePassFreq(widget.pass, currentValue.toInt(), isSend: true);
                                }))
                      ],
                    )),
                    Flexible(
                        child: Row(
                      children: [
                        Flexible(
                            flex: 2,
                            child: Align(alignment: Alignment.centerRight, child: Text('TYPE', style: fontNormal))),
                        const SizedBox(width: 10),
                        Flexible(
                          flex: 4,
                          child: Center(
                            child: Container(
                              height: 30,
                              decoration: boxDecoration(5),
                              child: Row(
                                children: [
                                  buildArrowBtn(true),
                                  Expanded(child: Center(child: Text('${widget.pass.type?.name}', style: fontNormal))),
                                  buildArrowBtn(false),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    )),
                    Flexible(
                      child: Row(
                        spacing: 5,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Flexible(
                            child: FittedBox(
                              fit: BoxFit.scaleDown,
                              child: Text(widget.pass.select ? 'ON' : 'OFF', style: fontNormal),
                            ),
                          ),
                          Flexible(
                            child: Transform.scale(
                                scale: 0.8,
                                child: Switch(
                                    value: widget.pass.select,
                                    onChanged: (value) => globalController.updatePassSwitch(widget.pass, value))),
                          ),
                          Flexible(
                            child: FittedBox(
                              fit: BoxFit.scaleDown,
                              child: Text('SLOPE', style: fontNormal),
                            ),
                          ),
                          SizedBox(
                            width: 160,
                            height: 30,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: widget.pass.type!.slopeList.map(($0) {
                                bool issame = widget.pass.type!.slope == $0;
                                return Container(
                                    padding: const EdgeInsets.only(left: 5),
                                    child: myTextButton(
                                        width: 35,
                                        height: 30,
                                        radius: 5,
                                        enable: widget.pass.select,
                                        color: issame ? const Color(0xFFE29D4F) : Colors.transparent,
                                        colors: [],
                                        child: Center(child: Text('${$0}', style: fontNormal)),
                                        onTap: () => globalController.updateSlope(widget.pass, $0)));
                              }).toList(),
                            ),
                          )
                        ],
                      ),
                    ),
                  ],
                ))
          ],
        ),
      );
    });
  }
}
